package com.gingko.duominuo.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo


private const val TAG = "NetworkUtils"

/**
 * 获取活动网络信息
 *
 * 需添加权限 `<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>`
 *
 * @param context 上下文
 * @return NetworkInfo
 */
private fun getActiveNetworkInfo(context: Context): NetworkInfo? {
    val cm = context
        .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    return cm.activeNetworkInfo
}

/**
 * 判断网络是否连接
 *
 * 需添加权限 `<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>`
 *
 * @param context 上下文
 * @return `true`: 是<br></br>`false`: 否
 */
fun isConnected(context: Context): Boolean {
    val networkInfo = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
    return networkInfo?.isConnected ?: false
}// ping的状态

/**
 * 判断网络是否可用
 *
 * 需添加权限 `<uses-permission android:name="android.permission.INTERNET"/>`
 *
 * @return `true`: 可用<br></br>`false`: 不可用
 */
val isAvailableByPing: Boolean
    get() {
        var process: Process? = null
        try {
            process = Runtime.getRuntime().exec("ping -c 1 -w 1 123.125.114.144")
            // ping的状态
            val status = process.waitFor()
            return status == 0
        } catch (e: Exception) {
            e.loge()
        } finally {
            process?.destroy()
        }
        return false
    }